package org.ilda.func.utility;


import java.io.IOException;
import java.io.UnsupportedEncodingException;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.entity.ContentType;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;

import com.ibm.icu.text.CharsetDetector;
import com.ibm.icu.text.CharsetMatch;


public class HttpUtility {
	
	/**
	 * 
	 * @param url
	 * @return
	 */
	public static HttpEntity getEntity(String url){
		HttpResponse response = null;
		HttpEntity entity = null;
		int statusCode = 0;
		HttpClient client = new DefaultHttpClient();
		HttpGet getMethod = new HttpGet(url);
		
		try {
			response = client.execute(getMethod);
			entity = response.getEntity();
		} catch (Exception e) {
			e.printStackTrace();
		} 
		
		statusCode = response.getStatusLine().getStatusCode();
		System.out.println("got response form url " + url + "  statusCode is: " + statusCode);
		
		if ((statusCode == HttpStatus.SC_MOVED_PERMANENTLY)
				|| (statusCode == HttpStatus.SC_MOVED_TEMPORARILY)
				|| (statusCode == HttpStatus.SC_SEE_OTHER)
				|| (statusCode == HttpStatus.SC_TEMPORARY_REDIRECT)) {	// 转向抓取新链接
		   return getEntity(response.getLastHeader("Location").getValue());
	     }
		else if(statusCode == HttpStatus.SC_NOT_FOUND){
			System.out.println("We can not found this page " + url);
		}
		if(entity != null){
			return entity;
		}else{
			return null;
		}
		
	}
	
	/**
	 * 
	 * @param entity
	 * @return
	 */
	public static String getContent(HttpEntity entity){
		byte [] bytes = null;
		String charSet = null;
		
		try {
			bytes = EntityUtils.toByteArray(entity);
			if(ContentType.getOrDefault(entity).getCharset() != null){
				charSet = ContentType.getOrDefault(entity).getCharset().toString();
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		
		if(charSet != null){
			try {
				return new String(bytes , charSet);
			} catch (UnsupportedEncodingException e) {
				e.printStackTrace();
			}
		}
		
		
		return getContent(bytes);
	}

	/**
	 * 
	 * @param bytes
	 * @return
	 */
	private static String getContent(byte[] bytes){
		CharsetDetector detector = new CharsetDetector();
		detector.setText(bytes);
		CharsetMatch match = detector.detect();
		
		try {
			return match.getString();
		} catch (IOException e) {
			e.printStackTrace();
		}
		return null;
	}
	

}
